<?php
require_once 'util/class.constants.php';
require_once 'util/class.simpleimage.php';

// ����ͼ�߼���������
$typeConfig = array (
		"main" => array(array("prefix"=>"s1","width"=>100, "height"=>100), 
					array("prefix"=>"s2", "width"=>200, "height"=>200)
				) 
		);

$result=array();
// �ж��Ƿ��ϴ��ɹ���
if ($_FILES["file"]["error"] > 0)
{
	$result['status']=$_FILES["file"]["error"];
}
else
{
	// �ж�ͼƬ���ͺʹ�С�Ƿ�֧��
	if ($_FILES["file"]["type"] != "image/gif"
		&& $_FILES["file"]["type"] != "image/jpeg"
		&& $_FILES["file"]["type"] != "image/pjpeg"
		&& $_FILES["file"]["type"] != "image/png") {
		$result['status']=Constants::$ERROR_UPLOAD_UNSOPPORT_FORMAT;
	} else if($_FILES["file"]["size"]>5000000) {
		$result['status']=Constants::$ERROR_UPLOAD_SIZE_TOOLARGE;
	} else {
		// ���ͼƬ�ĵ��ļ�������
		$time = time();
		$dirName = '../pic/'.date("Ymd", $time);
		if(!is_dir($dirName)) {
			mkdir($dirName, 0777, true);
		}
		// ���ͼƬ������
		$picBaseName = date("Ymd", $time).'-'.date('His',$time).'-';
		$start=0;
		$num = rand($start, $start+10000);
		$count=0;
		$picName = $picBaseName.$num.'.jpg';
		while(is_file($dirName.'/'.$picName)) {
			$num = rand($start, $start+10000);
			$picName = $picBaseName.$num.'.jpg';
			$count++;
			if($count % 10 == 0 ) {
				$start=$start+10000;
			}
			if($count==100)
				break;
		}
		
		$type=$_POST['type'];
		
		// ����ԭʼͼƬ
		move_uploaded_file($_FILES["file"]["tmp_name"], $dirName.'/'.$picName);
		// ���type��ɶ�Ӧ������ͼ
		$config = $typeConfig[$type];
		if($config!=null) {
			$image=new SimpleImage();
			$image->load($dirName.'/'.$picName);
			$newPicName=null;
			foreach($config as $item) {
				$newPicName = $item['prefix'].'-'.$picName;
				$scaleX = $item['width']*100/$image->getWidth();
				$scaleY = $item['height']*100/$image->getHeight();
				$newImage = $image->scaleAsNewImage(min($scaleX, $scaleY));
				$image->saveImage($newImage, $dirName.'/'.$newPicName);
			}
		}
		
		$result['status']=Constants::$SUCCESS;
		$result['data']=$picName;
	}
}

echo json_encode($result);
